from datetime import date, timedelta
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from users.models import User


# 用户总量统计
class UserTotalCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = User.objects.filter(is_staff=False).count()
        return Response({
            'count': count
        })


# 日增用户统计
class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        count = User.objects.filter(date_joined__gte=now_date, is_staff=False).count()
        return Response({
            'count': count,
            'date': now_date
        })


# 日活跃用户统计
class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(last_login__gte=now_date, is_staff=False).count()
        return Response({
            'count': count,
            'date': now_date
        })


# 日下单用户量统计
class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        count = len(set(User.objects.filter(orders__create_time__gte=now_date, is_staff=False)))
        return Response({
            'count': count,
            'date': now_date
        })


# 月增用户统计
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = date.today()
        # 一个月前的日期
        start_date = now_date - timedelta(30)
        date_list = []
        for i in range(31):
            # 循环遍历获取当前日期
            index_date = start_date + timedelta(i)
            # 获取下一天日期
            next_date = start_date + timedelta(i + 1)

            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date, is_staff=False).count()
            date_list.append({
                'count': count,
                'date': index_date
            })
        return Response(date_list)


# 日分类商品访问量
class GoodsDayView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, requset):
        now_date = date.today()
        goods_list = []
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        for good in goods:
            goods_list.append({
                'category': good.category.name,
                'count': good.count
            })
        return Response(goods_list)
